package com.fileupload.server;

import com.fileupload.config.ConfigReader;
import com.fileupload.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 连接管理器，负责管理所有服务器连接的缓存和生命周期
 * @author 小乙
 */
@Component
public class ConnectionManager {
    private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
    
    @Autowired
    private ConfigReader configReader;
    
    // 连接缓存，使用服务器名称作为key
    private Map<String, Connection> connectionCache = new HashMap<>();
    
    // 连接状态缓存，记录服务器连接状态
    private Map<String, Boolean> connectionStatus = new HashMap<>();
    
    // 线程锁，保证连接操作的线程安全
    private ReentrantLock lock = new ReentrantLock();
    
    @PostConstruct
    public void init() {
        logger.info("开始初始化连接管理器");
        
        // 初始化所有服务器连接
        Map<String, ServerConfig> serverConfigs = configReader.getAllServerConfigs();
        for (Map.Entry<String, ServerConfig> entry : serverConfigs.entrySet()) {
            String serverName = entry.getKey();
            ServerConfig config = entry.getValue();
            
            try {
                Connection connection = ConnectionFactory.createConnection(config);
                if (connection != null) {
                    boolean connected = connection.connect();
                    if (connected) {
                        lock.lock();
                        try {
                            connectionCache.put(serverName, connection);
                            connectionStatus.put(serverName, true);
                            logger.info("服务器[{}]初始化连接成功", serverName);
                        } finally {
                            lock.unlock();
                        }
                    } else {
                        connectionStatus.put(serverName, false);
                        logger.error("服务器[{}]初始化连接失败", serverName);
                    }
                } else {
                    connectionStatus.put(serverName, false);
                    logger.error("服务器[{}]无法创建连接", serverName);
                }
            } catch (IOException e) {
                connectionStatus.put(serverName, false);
                logger.error("服务器[{}]初始化连接异常: {}", serverName, e.getMessage());
            }
        }
        
        logger.info("连接管理器初始化完成");
    }
    
    /**
     * 获取指定服务器的配置
     */
    public ServerConfig getServerConfig(String serverName) {
        return configReader.getServerConfig(serverName);
    }
    public Connection getConnection(String serverName) {
        lock.lock();
        try {
            Connection connection = connectionCache.get(serverName);
            
            // 检查连接是否存在且有效
            if (connection != null && connection.isConnected()) {
                return connection;
            }
            
            // 如果连接不存在或已断开，尝试重新建立连接
            logger.info("尝试重新连接服务器: {}", serverName);
            ServerConfig serverConfig = configReader.getServerConfig(serverName);
            if (serverConfig == null) {
                logger.error("服务器配置不存在: {}", serverName);
                return null;
            }
            
            try {
                // 如果连接存在但已断开，先断开旧连接
                if (connection != null) {
                    try {
                        connection.disconnect();
                    } catch (IOException e) {
                        logger.error("断开旧连接异常: {}", e.getMessage());
                    }
                }
                
                // 创建新连接
                connection = ConnectionFactory.createConnection(serverConfig);
                if (connection != null) {
                    boolean connected = connection.connect();
                    if (connected) {
                        connectionCache.put(serverName, connection);
                        connectionStatus.put(serverName, true);
                        logger.info("服务器[{}]重新连接成功", serverName);
                        return connection;
                    } else {
                        connectionStatus.put(serverName, false);
                        logger.error("服务器[{}]重新连接失败", serverName);
                    }
                }
            } catch (IOException e) {
                connectionStatus.put(serverName, false);
                logger.error("服务器[{}]连接异常: {}", serverName, e.getMessage());
            }
            
            return null;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 检查服务器连接状态
     */
    public boolean isServerConnected(String serverName) {
        lock.lock();
        try {
            Boolean status = connectionStatus.get(serverName);
            return status != null && status;
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 关闭所有连接
     */
    public void closeAllConnections() {
        lock.lock();
        try {
            for (Map.Entry<String, Connection> entry : connectionCache.entrySet()) {
                String serverName = entry.getKey();
                Connection connection = entry.getValue();
                
                try {
                    if (connection != null) {
                        connection.disconnect();
                        logger.info("关闭服务器[{}]连接", serverName);
                    }
                } catch (IOException e) {
                    logger.error("关闭服务器[{}]连接异常: {}", serverName, e.getMessage());
                }
            }
            
            connectionCache.clear();
            connectionStatus.clear();
            logger.info("所有服务器连接已关闭");
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 获取所有连接状态
     */
    public Map<String, Boolean> getAllConnectionStatus() {
        lock.lock();
        try {
            return new HashMap<>(connectionStatus);
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 刷新指定服务器的连接
     */
    public boolean refreshConnection(String serverName) {
        lock.lock();
        try {
            // 移除旧连接
            Connection oldConnection = connectionCache.remove(serverName);
            if (oldConnection != null) {
                try {
                    oldConnection.disconnect();
                } catch (IOException e) {
                    logger.error("断开旧连接异常: {}", e.getMessage());
                }
            }
            
            // 创建新连接
            ServerConfig serverConfig = configReader.getServerConfig(serverName);
            if (serverConfig == null) {
                logger.error("服务器配置不存在: {}", serverName);
                return false;
            }
            
            try {
                Connection newConnection = ConnectionFactory.createConnection(serverConfig);
                if (newConnection != null) {
                    boolean connected = newConnection.connect();
                    if (connected) {
                        connectionCache.put(serverName, newConnection);
                        connectionStatus.put(serverName, true);
                        logger.info("服务器[{}]连接刷新成功", serverName);
                        return true;
                    } else {
                        connectionStatus.put(serverName, false);
                        logger.error("服务器[{}]连接刷新失败", serverName);
                    }
                }
            } catch (IOException e) {
                connectionStatus.put(serverName, false);
                logger.error("服务器[{}]连接刷新异常: {}", serverName, e.getMessage());
            }
            
            return false;
        } finally {
            lock.unlock();
        }
    }
}